use std::fs;
use std::io::{prelude::*, BufReader};
use std::net::{TcpListener, TcpStream};

fn main() {
    // 监听地址: 127.0.0.1:7878
    let listener = TcpListener::bind("127.0.0.1:7878").unwrap();

    for stream in listener.incoming() {
        let stream = stream.unwrap();
        handle_connection(stream);

        println!("Connection established!");
    }
}


fn handle_connection(mut stream: TcpStream) {
    let buf_reader = BufReader::new(&mut stream);
    let http_request: Vec<_> = buf_reader
        .lines()
        .map(|result| result.unwrap())
        .take_while(|line| !line.is_empty())
        .collect();

    println!("Request: {:#?}", http_request);

    let request_url = http_request[0].split(" ").nth(1).unwrap();

    println!("Request URL: {request_url}");

    // let status_line = "HTTP/1.1 200 OK";

    // let mut response = format!("{}{}", status_line, "\r\n");

    // if request_url == "/" {
    //     let contents = fs::read_to_string("E:\\workspace\\rust\\rust_net\\web_server_single_thread\\src\\index.html").unwrap();
    //     let length = contents.len();
    //
    //     response = format!("{status_line}\r\nContent-Length: {length}\r\n\r\n{contents}");
    // } else {
    //     println!("Request URL: {request_url}");
    //     let length = request_url.len();
    //     response = format!("{status_line}\r\nContent-Length: {length}\r\n\r\n{request_url}");
    // }


    let (status_line, filename) = if request_url == "/" {
        ("HTTP/1.1 200 OK", "E:\\workspace\\rust\\rust_net\\web_server_single_thread\\src\\index.html")
    } else {
        ("HTTP/1.1 404 NOT FOUND", "E:\\workspace\\rust\\rust_net\\web_server_single_thread\\src\\404.html")
    };

    let contents = fs::read_to_string(filename).unwrap();
    let length = contents.len();

    let response =
        format!("{status_line}\r\nContent-Length: {length}\r\n\r\n{contents}");

    stream.write_all(response.as_bytes()).unwrap();


    stream.write_all(response.as_bytes()).unwrap();
}